from django.shortcuts import render, redirect
from django.views import View

from author.models import Author, AuthorDetail


# Create your views here.
def author_detail(request):
    author_date = Author.objects.all()
    if request.method == "POST":
        author_id = request.POST.get("author_id") or request.POST.get("id")
        action = request.POST.get("action")
        author_obj = Author.objects.get(pk=author_id)
        author_obj_detail = AuthorDetail.objects.get(pk=author_obj.author_detail.pk)
        if action == 'update':
            data = request.POST
            author_obj.name = data.get('name')
            author_obj.age = data.get('age')
            for id, value in author_obj.gender_choices:
                if data.get('gender') == value:
                    author_obj.gender = id
                    break
            else:
                author_obj.gender=3
            author_obj.save()
            author_obj_detail.phone = data.get('phone')
            author_obj_detail.email = data.get('email')
            author_obj_detail.addr = data.get('addr')
            author_obj_detail.save()
        if action == 'del':
            author_obj.delete()
            author_obj_detail.delete()

    return render(request, 'author_detail.html', locals())


class AuthorAdd(View):
    def get(self, request, *args, **kwargs):
        author_all = Author.objects.all()
        return render(request, 'author_add.html', locals())

    def post(self, request, *args, **kwargs):
        data = request.POST
        name = data.get('name')
        age = data.get('age')
        gender = data.get('gender')
        phone = data.get('phone')
        email = data.get('email')
        addr = data.get('addr')
        Author_obj = AuthorDetail.objects.create(phone=phone, email=email, addr=addr)
        Author.objects.create(name=name, age=age, gender=gender, author_detail=Author_obj)
        return redirect('author_detail')
